const chunkSize = 5 * 1024 * 1024; // 每个分块大小 5MB
let fileName;
let totalChunks;
let downloadedChunks = 0;
let downloadUrl = "/file/downloadChunk";

// 输入文件名并开始下载
document.getElementById('fileName').addEventListener('change', (event) => {
    fileName = event.target.value;
    checkFileSize();
});

// 检查文件大小
async function checkFileSize() {
    try {
        const response = await fetch(`/file/downloadChunk?fileName=${fileName}&chunkIndex=0&chunkSize=1`);
        if (response.ok) {
            const contentLength = parseInt(response.headers.get('Content-Length'), 10);
            totalChunks = Math.ceil(contentLength / chunkSize);
            startDownload();
        } else {
            alert("文件不存在或无法下载！");
        }
    } catch (error) {
        console.error("检查文件大小失败", error);
    }
}

// 开始下载
async function startDownload() {
    downloadedChunks = 0;
    updateProgress(0);
    document.getElementById('status').innerText = "下载中...";

    const promises = [];
    for (let i = 0; i < totalChunks; i++) {
        promises.push(downloadChunk(i));
    }

    await Promise.all(promises);

    document.getElementById('status').innerText = "下载完成！";
    alert("文件下载完成！");
}

// 下载一个分块
async function downloadChunk(chunkIndex) {
    const response = await fetch(`${downloadUrl}?fileName=${fileName}&chunkIndex=${chunkIndex}&chunkSize=${chunkSize}`);

    if (!response.ok) {
        console.error(`下载分块失败，分块索引: ${chunkIndex}`);
        return;
    }

    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = fileName;  // 使用原文件名进行下载
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);

    downloadedChunks++;
    updateProgress((downloadedChunks / totalChunks) * 100);
}

// 更新进度条
function updateProgress(percentage) {
    document.getElementById('progress-bar').style.width = percentage + "%";
}
